package com.samp.bblock.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * AesCbc加密算法
 */
public class AesCbcUtil {
    private static final Logger logger = LoggerFactory.getLogger(AesCbcUtil.class);
    /**
     * 密钥算法
     */
    public static final String KEY_ALGORITHM = "AES";

    /**
     * 加解密算法/工作模式/填充方式,Java6.0支持PKCS5Padding填充方式,BouncyCastle支持PKCS7Padding填充方式
     */
    public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * 字符编码
     */
    public static final String UTF8 = "UTF-8";

    /**
     * 填充矢量
     */
    private static final byte[] IV = {0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31};

    /**
     * 密钥生成器
     * java6只支持56位密钥，bouncycastle支持64位密钥
     *
     * @return
     */
    public static byte[] initkey() {
        //实例化密钥生成器官
        KeyGenerator keyGen = null;
        try {
            keyGen = KeyGenerator.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            logger.error("initKey", e);
        }
        //初始化密钥生成器,AES要求密钥长度为128位\192位\256位
        keyGen.init(128);
        //生成密钥
        SecretKey secretKey = keyGen.generateKey();
        //获取二进制密钥编码
        byte[] key = secretKey.getEncoded();
        return key;
    }

    /**
     * 转换密钥
     *
     * @param key 二进制密钥
     * @return Key 密钥
     */
    private static Key toKey(byte[] key) {
        //如果密钥不足16位,那么补足
        int base = 16;
        if (key.length % base != 0) {
            int groups = (key.length / base) + key.length % base != 0 ? 1 : 0;
            byte[] temp = new byte[groups * base];
            //数组填充方法
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }
        SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
        return secretKey;
    }

    /**
     * 密钥通过MD5处理为16位,再进行加密
     *
     * @param data
     * @param key
     * @return
     */
    public static String secretKey16Encrypt(String data, String key) {
        if (StringUtils.isBlank(data)) {
            return data;
        }
        key = Md5Util.secretKey16(key);
        return encrypt(data, key);
    }

    /**
     * 数据加密
     *
     * @param data 待加密数据
     * @param key  密钥
     * @return String 加密后的数据
     */
    public static String encrypt(String data, String key) {
        String encryptStr = "";
        try {
            byte[] enc = encrypt(data.getBytes(UTF8), key.getBytes(UTF8));
            String hexStr = HexUtil.encodeHexStr(enc);
            encryptStr = new String(hexStr.getBytes(UTF8), UTF8);
        } catch (UnsupportedEncodingException e) {
            logger.error("encrypt data[" + data + "],key[请查密钥]进行getBytes(utf-8) error.", e);
        }
        return encryptStr;
    }

    /**
     * 数据加密
     *
     * @param data 待加密数据
     * @param key  密钥
     * @return byte[] 加密后的数据
     */
    public static byte[] encrypt(byte[] data, byte[] key) {
        //密钥
        Key k = toKey(key);
        /**
         * 实例化 
         * 使用 PKCS7PADDING 填充方式，按如下方式实现,就是调用bouncycastle组件实现 
         * Cipher.getInstance(CIPHER_ALGORITHM,"BC") 
         */
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            logger.error("encrypt Cipher.getInstance error", e);
        } catch (NoSuchPaddingException e) {
            logger.error("encrypt Cipher.getInstance error,", e);
        }
        //初始化，设置为加密模式  
        try {
            cipher.init(Cipher.ENCRYPT_MODE, k, new IvParameterSpec(IV));
        } catch (InvalidKeyException e) {
            logger.error("encrypt cipher.init(Cipher.ENCRYPT_MODE, k) error,", e);
        } catch (InvalidAlgorithmParameterException e) {
            logger.error("encrypt cipher.init(Cipher.ENCRYPT_MODE, k, new IvParameterSpec(IV)) error", e);
        }
        //执行操作  
        try {
            return cipher.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            logger.error("encrypt cipher.doFinal() error,param[" + data + "]", e);
        } catch (BadPaddingException e) {
            logger.error("encrypt cipher.doFinal() error,param[" + data + "]", e);
        }
        return null;
    }

    /**
     * 密钥通过MD5处理为16位,再进行解密
     *
     * @param data
     * @param key
     * @return
     */
    public static String secretKey16Decrypt(String data, String key) {
        if (StringUtils.isBlank(data)) {
            return data;
        }
        key = Md5Util.secretKey16(key);
        return decrypt(data, key);
    }

    /**
     * 解密数据
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return String 解密后的数据
     */
    public static String decrypt(String data, String key) {
        String decryptStr = "";
        try {
            byte[] enc = HexUtil.decodeHex(data.toCharArray());
            byte[] dec = decrypt(enc, key.getBytes(UTF8));
            decryptStr = new String(dec, UTF8);
        } catch (RuntimeException ex) {
            logger.warn("HexUtil.decodeHex(data.toCharArray()) error [data={}]", data, ex);
        } catch (UnsupportedEncodingException e) {
            logger.error("decrypt [data={}],key[请查密钥]进行getBytes(utf-8) [error={}]", data, e);
        }
        return decryptStr;
    }

    /**
     * 解密数据
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[] 解密后的数据
     */
    public static byte[] decrypt(byte[] data, byte[] key) {
        //密钥
        Key k = toKey(key);
        /**
         * 实例化 
         * 使用 PKCS7PADDING 填充方式，按如下方式实现,就是调用bouncycastle组件实现 
         * Cipher.getInstance(CIPHER_ALGORITHM,"BC") 
         */
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            logger.error("decrypt Cipher.getInstance error", e);
        } catch (NoSuchPaddingException e) {
            logger.error("decrypt Cipher.getInstance error,", e);
        }
        //初始化，设置为解密模式  
        try {
            cipher.init(Cipher.DECRYPT_MODE, k, new IvParameterSpec(IV));
        } catch (InvalidKeyException e) {
            logger.error("decrypt cipher.init(Cipher.DECRYPT_MODE, k) error,", e);
        } catch (InvalidAlgorithmParameterException e) {
            logger.error("decrypt cipher.init(Cipher.DECRYPT_MODE, k,new IvParameterSpec(IV)) error", e);
        }
        //执行操作  
        try {
            return cipher.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            logger.error("decrypt cipher.doFinal() error,param[" + data + "]", e);
        } catch (BadPaddingException e) {
            logger.error("decrypt cipher.doFinal() error,param[" + data + "]", e);
        }
        return null;
    }
    
    public static void main(String[] args){
        System.out.println(AesCbcUtil.secretKey16Encrypt("371052", "Dq!w4tg&ty90pI6G"));
    }
}
